<template>
  <div :id="name" class="chart-container"></div>
</template>
<script>
import { Column } from '@antv/g2plot'
export default {
  data () {
    return {
      columnPlot: null,
    }
  },
  props: {
    name: {
      type: String,
      default: 'BarCanvas'
    },
    data: {
      type: Array,
      default: () => []
    },
    yAlias: {
      type: String,
      default: '金额'
    },
    unit: {
      type: String,
      default: ' 元'
    },
    yAxisStyle: {
      type: Object,
      default: () => ({
        stroke: 'black',
        lineWidth: 1,
        lineDash: [2, 2],
        opacity: 0.15,
        cursor: 'pointer'
      })
    },
    columnWidthRatio: {
      type: Number,
      default: 0.6
    }
  },
  mounted() {
    this.columnPlot = new Column(this.name, {
      data: this.data,
      xField: 'x',
      yField: 'y',
      color: '#019cf6',
      xAxis: {
        label: {
          autoHide: true,
          autoRotate: false,
        }
      },
      yAxis: {
        grid: {
          line: {
            style: this.yAxisStyle
          }
        }
      },
      label: {
        // 可手动配置 label 数据标签位置
        position: 'middle', // 'top', 'middle', 'bottom'
        // 可配置附加的布局方法
        layout: [
          // 柱形图数据标签位置自动调整
          { type: 'interval-adjust-position' },
          // 数据标签防遮挡
          { type: 'interval-hide-overlap' },
          // 数据标签文颜色自动调整
          { type: 'adjust-color' },
        ],
      },
      columnWidthRatio: this.columnWidthRatio,
      tooltip: {
        formatter: (datum) => {
          return { name: this.yAlias, value: this.thousands(datum.y) + this.unit };
        }
      },
      meta: {
        x: {
          alias: '月份',
        },
        y: {
          alias: this.yAlias,
          formatter: (val) => {
            return this.thousands(val);
          }
        }
      }
    })
    this.columnPlot.render()
  },
  methods: {
    thousands: function (num) {
      var str = num.toString();
      var reg = str.indexOf(".") > -1 ? /(\d)(?=(\d{3})+\.)/g : /(\d)(?=(?:\d{3})+$)/g;
      return str.replace(reg,"$1,");
    }
  }
}
</script>
<style lang="scss" scoped>
.chart-container {
  width: 100%;
  height: 100%;
}
</style>
